import pandas as pd
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter import ttk
import os

def load_mapping_from_csv(cities_file):
    """从 cities.csv 读取身份证前4位与省市的映射关系"""
    cities_df = pd.read_csv(cities_file, dtype={"number": str, "name": str})
    mapping = {}
    for _, row in cities_df.iterrows():
        mapping[row["number"][:4]] = row["name"]
    return mapping

def get_region_from_id_prefix(id_prefix, mapping):
    """根据身份证前4位获取省市信息"""
    return mapping.get(str(id_prefix)[:4], "未知区域")

def process_excel(file_path, cities_file):
    """读取 Excel 并添加省市信息"""
    mapping = load_mapping_from_csv(cities_file)
    df = pd.read_excel(file_path, header=None, dtype=str)
    df.columns = ['身份证前6位']  # 假设数据在第一列
    df['省市'] = df['身份证前6位'].apply(lambda x: get_region_from_id_prefix(x, mapping))

    # 将结果保存到当前目录下的 output.xlsx
    output_path = os.path.join(os.getcwd(), "output.xlsx")
    df.to_excel(output_path, index=False, header=False)  # 输出时不包含标题行
    messagebox.showinfo("完成", f"处理完成，结果已保存至 {output_path}")

class IDCardProcessorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("身份证省市信息处理器")
        self.root.geometry("400x250")
        self.root.resizable(False, False)

        # 输入文件路径
        self.input_file_path = ""
        self.cities_file_path = ""

        # 创建并放置界面元素
        self.create_widgets()

    def create_widgets(self):
        # 设置背景色
        self.root.configure(bg="#f0f0f0")

        # 标题标签
        title_label = tk.Label(self.root, text="身份证省市信息处理", font=("Arial", 16, "bold"), bg="#f0f0f0", fg="#333")
        title_label.pack(pady=20)

        # 输入文件选择按钮
        self.input_button = ttk.Button(self.root, text="选择输入 Excel 文件", command=self.select_input_file, width=30)
        self.input_button.pack(pady=10)

        # 城市 CSV 文件选择按钮
        self.cities_button = ttk.Button(self.root, text="选择 id_card.csv 文件", command=self.select_cities_file, width=30)
        self.cities_button.pack(pady=10)

        # 开始处理按钮
        self.process_button = ttk.Button(self.root, text="开始处理", command=self.process_files, width=30)
        self.process_button.pack(pady=20)

    def select_input_file(self):
        """选择输入 Excel 文件"""
        self.input_file_path = filedialog.askopenfilename(filetypes=[("Excel Files", "*.xlsx")])
        if self.input_file_path:
            print(f"选中的输入文件: {self.input_file_path}")

    def select_cities_file(self):
        """选择城市 CSV 文件"""
        self.cities_file_path = filedialog.askopenfilename(filetypes=[("CSV Files", "*.csv")])
        if self.cities_file_path:
            print(f"选中的城市文件: {self.cities_file_path}")

    def process_files(self):
        """开始处理文件"""
        if not self.input_file_path or not self.cities_file_path:
            messagebox.showerror("错误", "请确保选择了所有必需的文件！")
            return
        try:
            process_excel(self.input_file_path, self.cities_file_path)
        except Exception as e:
            messagebox.showerror("错误", f"处理过程中出现错误: {str(e)}")

# 启动 GUI 应用程序
if __name__ == "__main__":
    root = tk.Tk()
    app = IDCardProcessorApp(root)
    root.mainloop()
